import styled from "@emotion/styled"
import { AnimatePresence, motion } from "motion/react"
import { Outlet, useLocation, useMatch } from "react-router-dom"

const variants = {
    hidden: { opacity: 0, x: 0, y: 20 },
    enter: { opacity: 1, x: 0, y: 0 },
    exit: { opacity: 0, x: 0, y: 20 },
}

const CurrentContainer = styled(motion.div)`
    flex: 1;
    display: flex;
    flex-direction: column;
`

type Props = ExtractStyledProps<typeof CurrentContainer>

function AnimatedLayout({ children }: Props) {
    return (
        <AnimatePresence mode="wait">
            <CurrentContainer
                initial="hidden"
                animate="enter"
                exit="exit"
                variants={variants}
                transition={{ duration: 0.5, type: "easeInOut" }}
            >
                {children}
            </CurrentContainer>
        </AnimatePresence>
    )
}

export function AnimatedLayoutWithOutlet({
    dependency = "pathname",
}: {
    dependency?: keyof Pick<ReturnType<typeof useLocation>, "pathname" | "search">
}) {
    const location = useLocation()
    return (
        <AnimatedLayout key={location[dependency]}>
            <Outlet />
        </AnimatedLayout>
    )
}

export function AnimatedLayoutWithOutletPattern({ base = "" }) {
    const match = useMatch(`${base ?? ""}/:dependency`)
    return (
        <AnimatedLayout key={match?.params.dependency}>
            <Outlet />
        </AnimatedLayout>
    )
}

export default AnimatedLayout
